#ifndef __M_SERVER_H__
#define __M_SERVER_H__
#include <iostream>
#include <vector>
#include <unordered_map>
#include <cstdint>
#include <cassert>
#include <string>
#include <cstring>
#include <ctime>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <functional>
#include <sys/epoll.h>
#include <signal.h>
#include <mutex>
#include <thread>
#include <condition_variable>
#include <sys/eventfd.h>
#include <sys/timerfd.h>

enum
{
    INFO,
    DEBUG,
    ERROR
};

#define LOG_LEVEL INFO
#define LOG(level, format, ...)                                                                                        \
    do                                                                                                                 \
    {                                                                                                                  \
        if (level < LOG_LEVEL)                                                                                         \
            break;                                                                                                     \
        time_t t = time(NULL);                                                                                         \
        struct tm *ltm = localtime(&t);                                                                                \
        char tmp[32] = {0};                                                                                            \
        strftime(tmp, 31, "%H:%M:%S", ltm);                                                                            \
        fprintf(stdout, "[%p %s %s:%d] " format "\n", (void *)pthread_self(), tmp, __FILE__, __LINE__, ##__VA_ARGS__); \
    } while (0)

#define BUFFER_DEFAULT_SIZE 1024
class Buffer
{
private:
    std::vector<char> _buffer; // 使用vector进行内存管理
    uint64_t _reader_index;    // 读偏移
    uint64_t _writer_index;    // 写偏移
public:
    Buffer() : _reader_index(0), _writer_index(0), _buffer(BUFFER_DEFAULT_SIZE) {}
    char *Begin() { return &*_buffer.begin(); }
    uint64_t ReadAbleSize() { return _writer_index - _reader_index; } // 获取可读数据大小

    // 获取当前写入起始地址
    char *WritePosition() { return Begin() + _writer_index; }
    // 获取当前读取起始地址
    char *ReadPosition() { return Begin() + _reader_index; }

    // 获取缓冲区末尾空闲空间大小--写偏移之后的空闲空间
    uint64_t AvailableTailSpace() { return _buffer.size() - _writer_index; }
    // 获取缓冲区起始空闲空间大小--读偏移之前的空闲空间
    uint64_t AvailableHeadSpace() { return _reader_index; }

    // 将读偏移向后移动
    void MoveReadOffset(uint64_t len)
    {
        if (len == 0)
            return;
        assert(len <= ReadAbleSize());
        _reader_index += len;
    }
    // 将写偏移向后移动
    void MoveWriteOffset(uint64_t len)
    {
        assert(len <= AvailableTailSpace());
        _writer_index += len;
    }

    // 确保可写空间足够
    void EnsureWritableSpace(uint64_t len)
    {
        // 如果末尾空闲空间大小足够，直接返回
        if (len <= AvailableTailSpace())
        {
            return;
        }
        // 若head和tail加起来空间足够，将数据移动到起始位置
        if (len <= AvailableHeadSpace() + AvailableTailSpace())
        {
            uint64_t rsz = ReadAbleSize();                            // 保存数据大小
            std::copy(ReadPosition(), ReadPosition() + rsz, Begin()); // 可读数据拷贝到起始位置
            _reader_index = 0;
            _writer_index = rsz; // 将写位置置为可读数据大小
        }
        else
        {
            LOG(DEBUG, "resize %ld", _writer_index + len);
            _buffer.resize(_writer_index + len);
        }
    }
    // 写入数据
    void WriteData(const void *data, uint64_t len)
    {
        if (len == 0)
            return;
        // 确保足够的空间拷贝
        EnsureWritableSpace(len);
        const char *datatmp = (const char *)data;
        std::copy(datatmp, datatmp + len, WritePosition());
    }
    void WriteAndPush(const void *data, uint64_t len)
    {
        WriteData(data, len);
        MoveWriteOffset(len);
    }
    void WriteString(const std::string &data)
    {
        WriteData(data.c_str(), data.size());
    }
    void WriteStringAndPush(const std::string &data)
    {
        WriteString(data);
        MoveWriteOffset(data.size());
    }
    void WriteBuffer(Buffer &data)
    {
        WriteData(data.ReadPosition(), data.ReadAbleSize());
    }
    void WriteBufferAndPush(Buffer &data)
    {
        WriteBuffer(data);
        MoveWriteOffset(data.ReadAbleSize());
    }
    // 读取数据
    void ReadData(void *buf, uint64_t len)
    {
        // 要求获取的数据大小必须小于可读数据大小
        assert(len <= ReadAbleSize());
        std::copy(ReadPosition(), ReadPosition() + len, (char *)buf);
    }
    void ReadAndPop(void *buf, uint64_t len)
    {
        ReadData(buf, len);
        MoveReadOffset(len);
    }
    std::string ReadAsString(uint64_t len)
    {
        assert(len <= ReadAbleSize());
        std::string str;
        str.resize(len);
        ReadData(&str[0], len);
        return str;
    }
    std::string ReadAsStringAndPop(uint64_t len)
    {
        assert(len <= ReadAbleSize());
        std::string ret = ReadAsString(len);
        MoveReadOffset(len);
        return ret;
    }
    char *FindCRLF()
    {
        // 找到换行符
        void *res = (char *)memchr(ReadPosition(), '\n', ReadAbleSize());
        return (char *)res;
    }
    // 获取一行数据
    std::string GetLine()
    {
        char *pos = FindCRLF();
        if (pos == NULL)
            return "";
        return ReadAsString(pos - ReadPosition() + 1); // 把换行字符也取出
    }
    std::string GetLineAndPop()
    {
        std::string str = GetLine();
        MoveReadOffset(str.size());
        return str;
    }

    // 清空缓冲区
    void clearBuffer()
    {
        _reader_index = 0;
        _writer_index = 0;
    }
};

#define MAX_LISTEN 1024
class Socket
{
private:
    int _sockfd;

public:
    Socket() : _sockfd(-1) {}
    Socket(int fd) : _sockfd(fd) {}
    ~Socket() { Close(); }
    int Fd() { return _sockfd; }
    // 创建套接字
    bool Create()
    {
        _sockfd = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if (_sockfd < 0)
        {
            LOG(ERROR, "create socket failed!");
            return false;
        }
        return true;
    }
    // 绑定地址信息
    bool Bind(const std::string &ip, uint16_t port)
    {
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        addr.sin_addr.s_addr = inet_addr(ip.c_str());
        socklen_t len = sizeof(struct sockaddr_in);
        int ret = bind(_sockfd, (struct sockaddr *)&addr, len);
        if (ret < 0)
        {
            LOG(ERROR, "bind address failed!");
            return false;
        }
        return true;
    }
    // 开始监听
    bool Listen(int backlog = MAX_LISTEN)
    {
        int ret = listen(_sockfd, backlog);
        if (ret < 0)
        {
            LOG(ERROR, "socket listen error!");
            return false;
        }
        return true;
    }
    // 向服务器发起连接
    bool Connect(const std::string &ip, uint16_t port)
    {
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        addr.sin_addr.s_addr = inet_addr(ip.c_str());
        socklen_t len = sizeof(struct sockaddr_in);
        int ret = connect(_sockfd, (const sockaddr *)&addr, len);
        if (ret < 0)
        {
            LOG(ERROR, "connnect server failed!");
            return false;
        }
        return true;
    }
    // 获取新连接
    int Accept()
    {
        int newfd = accept(_sockfd, NULL, NULL);
        if (newfd < 0)
        {
            LOG(ERROR, "accept failed");
            return -1;
        }
        return newfd;
    }
    // 接收数据
    ssize_t Recv(void *buff, size_t len, int flag = 0)
    {
        ssize_t ret = recv(_sockfd, buff, len, flag);
        if (ret <= 0)
        {
            // 非阻塞型 I/O 操作时，如果操作不能立即完成，就会返回 EAGAIN(无数据可读）
            // 进程收到了一个信号，并且该信号被处理，那么系统调用可能会被中断，并返回 EINTR（被信号打断）
            if (errno == EAGAIN || errno == EINTR)
                return 0;
            LOG(ERROR, "socket recv failed");
            return -1;
        }
        return ret;
    }
    ssize_t NoBlockRecv(void *buff, size_t len)
    {
        return Recv(buff, len, MSG_DONTWAIT); // MSG_DONTWAIT表示当前接收为非阻塞
    }
    // 发送数据
    ssize_t Send(const void *buff, size_t len, int flag = 0)
    {
        ssize_t ret = send(_sockfd, buff, len, flag);
        if (ret < 0)
        {
            if (errno == EAGAIN || errno == EINTR)
                return 0;
            LOG(ERROR, "socket send failed");
            return -1;
        }
        return ret;
    }
    ssize_t NonBlockSend(void *buff, size_t len)
    {
        if (len == 0)
            return 0;
        return Send(buff, len, MSG_DONTWAIT); // MSG_DONTWAIT
    }
    // 接收数据
    void Close()
    {
        if (_sockfd != -1)
        {
            ::close(_sockfd);
            _sockfd = -1;
        }
    }
    // 创建服务端连接
    bool CreateServer(uint16_t port, const std::string &ip = "0.0.0.0", bool block_flag = false)
    {
        // 创建套接字-绑定地址-开始监听-设置非阻塞-启动地址重用
        if (Create() == false)
            return false;
        if (block_flag)
            NonBlock();
        if (Bind(ip, port) == false)
            return false;
        if (Listen() == false)
            return false;
        ReuseAddress();
        return true;
    }
    // 创建客户端连接
    bool CreateClient(uint16_t port, const std::string &ip)
    {
        // 创建套接字-连接服务器
        if (Create() == false)
            return false;
        if (Connect(ip, port) == false)
            return false;
        return true;
    }
    // 设置套接字选项--开启地址端口重用
    void ReuseAddress()
    {
        int val = 1;
        setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, (void *)&val, sizeof(int));
        val = 1;
        setsockopt(_sockfd, SOL_SOCKET, SO_REUSEPORT, (void *)&val, sizeof(int));
    }
    // 设置套接字阻塞属性--设置为非阻塞
    void NonBlock()
    {
        int flag = fcntl(_sockfd, F_GETFL, 0);
        fcntl(_sockfd, F_SETFL, flag | O_NONBLOCK);
    }
};

class Poller;
class EventLoop;
class Channel
{
private:
    int _fd;
    EventLoop *_loop;
    uint32_t _events;  // 当前需要监控的事件
    uint32_t _revents; // 当前连接触发的事件
    using EventCallBack = std::function<void()>;
    EventCallBack _read_callback;  // 可读事件被触发
    EventCallBack _write_callback; // 可写事件被触发
    EventCallBack _error_callback; // 错误事件被触发
    EventCallBack _close_callback; // 断开连接
    EventCallBack _event_callback; // 任意事件
public:
    Channel(EventLoop *loop, int fd) : _fd(fd), _events(0), _revents(0), _loop(loop) {}
    int Fd() { return _fd; }
    void SetRevents(uint32_t events) { _revents = events; }
    uint32_t Events() { return _events; }
    void SetReadCallBack(const EventCallBack &cb) { _read_callback = cb; }
    void SetWriteCallBack(const EventCallBack &cb) { _write_callback = cb; }
    void SetErrorCallBack(const EventCallBack &cb) { _error_callback = cb; }
    void SetCloseCallBack(const EventCallBack &cb) { _close_callback = cb; }
    void SetEventCallBack(const EventCallBack &cb) { _event_callback = cb; }
    // 确认是否监控可读
    bool Readable() { return (_events & EPOLLIN); }
    // 确认是否可写
    bool Writeable() { return (_events & EPOLLOUT); }
    // 启动读事件监控
    void EnableRead()
    {
        _events |= EPOLLIN;
        Update();
    }
    // 启动写事件监控
    void EnableWrite()
    {
        _events |= EPOLLOUT;
        Update();
    }
    // 关闭读监控
    void DisableRead()
    {
        _events &= ~EPOLLIN;
        Update();
    }
    // 关闭写监控
    void DisableWrite()
    {
        _events &= ~EPOLLOUT;
        Update();
    }
    // 关闭所有事件监控
    void DisableAll()
    {
        _events = 0;
        Update();
    }
    // 移出监控
    void Remove();
    void Update();
    // 事件处理，一旦触发某个事件就调用这个函数
    void HandleEvent()
    {
        if ((_revents & EPOLLIN) || (_revents & EPOLLHUP) || (_revents & EPOLLPRI))
        {
            if (_read_callback)
                _read_callback();
        }
        if (_revents & EPOLLOUT)
        {
            if (_write_callback)
                _write_callback();
        }
        // 有可能会释放连接的操作事件，一次只处理一个
        else if (_revents & EPOLLHUP)
        {
            if (_close_callback)
                _close_callback(); // 一旦出错就会释放连接，没必要调用任意回调了
        }
        else if (_revents & EPOLLERR)
        {
            if (_error_callback)
                _error_callback();
        }
        if (_event_callback)
            _event_callback();
    }
};

#define MAX_EPOLLEVENTS 1024
class Poller
{
    // 用于描述符事件监控
private:
    int _epfd;
    struct epoll_event _events[MAX_EPOLLEVENTS];
    std::unordered_map<int, Channel *> _channels;

private:
    // 对epoll的直接操作
    void Update(Channel *channel, int oper)
    {
        int fd = channel->Fd();
        struct epoll_event ev;
        ev.data.fd = fd;
        ev.events = channel->Events();
        int ret = epoll_ctl(_epfd, oper, fd, &ev);
        if (ret < 0)
        {
            LOG(ERROR, "epollctl failed");
            abort();
        }
    }
    // 判断一个channel是否已经添加了事件监控
    bool HasChannel(Channel *channel)
    {
        auto it = _channels.find(channel->Fd());
        if (it == _channels.end())
            return false;
        return true;
    }

public:
    Poller()
    {
        _epfd = epoll_create(MAX_EPOLLEVENTS);
        if (_epfd < 0)
        {
            LOG(ERROR, "epoll create fail");
            abort();
        }
    }
    // 添加或修改监控事件
    void UpdateEvents(Channel *channel)
    {
        bool ret = HasChannel(channel);
        if (ret == false)
        {
            _channels.insert(std::make_pair(channel->Fd(), channel));
            return Update(channel, EPOLL_CTL_ADD); // 不存在则添加
        }
        Update(channel, EPOLL_CTL_MOD);
    }
    // 删除监控事件
    void RemoveEvent(Channel *channel)
    {
        auto it = _channels.find(channel->Fd());
        if (it != _channels.end())
            _channels.erase(it);
        Update(channel, EPOLL_CTL_DEL);
    }

    // 开始监控，返回活跃连接
    void Poll(std::vector<Channel *> *active)
    {
        int nfds = epoll_wait(_epfd, _events, MAX_EPOLLEVENTS, -1);
        if (nfds < 0)
        {
            if (errno == EINTR)
            {
                return;
            }
            LOG(ERROR, "epoll wait error:%s\n", strerror(errno));
            abort();
        }
        for (int i = 0; i < nfds; ++i)
        {
            auto it = _channels.find(_events[i].data.fd);
            assert(it != _channels.end());
            it->second->SetRevents(_events[i].events);
            active->push_back(it->second);
        }
    }
};

using TaskFunc = std::function<void()>;
using ReleaseFunc = std::function<void()>;
class TimerTask
{
private:
    uint64_t _id;         // 定时器任务对象ID
    uint32_t _timeout;    // 定时任务的超时时间
    bool _canceled;       // true-表示被取消
    TaskFunc _task_cb;    // 定时器对象要执行的定时任务
    ReleaseFunc _release; // 用于删除TimerWheel中保存的定时器对象信息
public:
    TimerTask(uint64_t id, uint32_t delay, const TaskFunc &cb)
        : _id(id), _timeout(delay), _task_cb(cb), _canceled(false)
    {
    }
    ~TimerTask()
    {
        if (_canceled == false)
            _task_cb();
        _release();
    }

    void Cancel() { _canceled = true; }
    void SetRelease(const ReleaseFunc &cb) { _release = cb; }
    uint32_t DelayTime() { return _timeout; }
};

class TimerWheel
{
private:
    using WeakTask = std::weak_ptr<TimerTask>;
    using PtrTask = std::shared_ptr<TimerTask>;
    int _tick;     // 当前的秒针，走到哪里释放哪里，释放哪里，就相当于执行哪里的任务
    int _capacity; // 表盘最大数量 其实就是最大延迟时间

    std::vector<std::vector<PtrTask>> _wheel;
    std::unordered_map<uint64_t, WeakTask> _timers;

    EventLoop *_loop;
    int _timerfd; // 定时器描述符-可读事件回调就是读取计时器，执行定时任务
    std::unique_ptr<Channel> _timer_channel;

private:
    void RemoveTimer(uint64_t id)
    {
        auto it = _timers.find(id);
        if (it != _timers.end())
        {
            _timers.erase(it);
        }
    }
    static int CreateTimerfd()
    {
        int timerfd = timerfd_create(CLOCK_MONOTONIC, 0);
        if (timerfd < 0)
        {
            LOG(ERROR, "timerfd create failed");
            abort();
        }
        // int timerfd_settime(int fd, int flags, struct itimerspec *new, struct itimerspec *old);
        struct itimerspec itime;
        itime.it_value.tv_sec = 1;
        itime.it_value.tv_nsec = 0; // 第一次超时时间为1s后
        itime.it_interval.tv_sec = 1;
        itime.it_interval.tv_nsec = 0; // 第一次超时后，每次超时的间隔时
        timerfd_settime(timerfd, 0, &itime, NULL);
        return timerfd;
    }
    int ReadTimefd()
    {
        uint64_t times;
        int ret = read(_timerfd, &times, 8);
        if (ret < 0)
        {
            LOG(ERROR, "read timerfd failed");
            abort();
        }
        return times;
    }
    // 这个函数应该每秒钟被执行一次，相当于秒针向后走了一步
    void RunTimerTask()
    {
        _tick = (_tick + 1) % _capacity;
        _wheel[_tick].clear(); // 清空指定位置的数组，就会把数组中保存的所有管理定时器对象的shared_ptr释放掉
    }
    void Ontime()
    {
        // 根据实际超时的次数，执行对应的超时任务
        int times = ReadTimefd();
        for (int i = 0; i < times; i++)
            RunTimerTask();
    }
    void TimerAddInLoop(uint64_t id, uint32_t delay, const TaskFunc &cb)
    {
        PtrTask pt(new TimerTask(id, delay, cb));
        pt->SetRelease(std::bind(&TimerWheel::RemoveTimer, this, id));
        int pos = (_tick + delay) % _capacity;
        _wheel[pos].push_back(pt);
        _timers[id] = WeakTask(pt);
    }
    void TimerRefreshInLoop(uint64_t id)
    {
        // 通过保存的定时器对象的weak_ptr构造一个shared_ptr出来，添加到轮子中
        auto it = _timers.find(id);
        if (it == _timers.end())
            return;                     // 没找着定时任务，没法刷新，没法延迟
        PtrTask pt = it->second.lock(); // lock获取weak_ptr管理的对象对应的shared_ptr
        int delay = pt->DelayTime();
        int pos = (_tick + delay) % _capacity;
        _wheel[pos].push_back(pt);
    }
    void TimerCancelInLoop(uint64_t id)
    {
        auto it = _timers.find(id);
        if (it == _timers.end())
            return; // 没找着定时任务，没法刷新，没法延迟
        PtrTask pt = it->second.lock();
        if (pt)
            pt->Cancel();
    }

public:
    TimerWheel(EventLoop *loop)
        : _capacity(60), _tick(0), _wheel(_capacity), _loop(loop),
          _timerfd(CreateTimerfd()), _timer_channel(new Channel(_loop, _timerfd))
    {
        _timer_channel->SetReadCallBack(std::bind(&TimerWheel::Ontime, this));
        _timer_channel->EnableRead(); // 启动读事件监控
    }
    void TimerAdd(uint64_t id, uint32_t delay, const TaskFunc &cb);
    // 刷新/延迟定时任务
    void TimerRefresh(uint64_t id);
    void TimerCancel(uint64_t id);
    // 这个接口存在线程安全问题，不能被外界使用者调用，只能在模块内，在对应的EventLoop线程内执行
    bool HasTimer(uint64_t id)
    {
        auto it = _timers.find(id);
        if (it == _timers.end())
            return false;
        return true;
    }
};

using Functor = std::function<void()>;

class EventLoop
{
    // 对所有描述符进行监控，执行任务队列中的任务
private:
    std::thread::id _thread_id; // 线程ID
    Poller _poller;             // 进行描述符的事件监控
    int _event_fd;              // eventfd唤醒IO事件监控有可能导致的阻塞
    std::unique_ptr<Channel> _event_channel;

    std::vector<Functor> _tasks; // 任务池
    std::mutex _mutex;           // 实现任务池操作的线程安全
    TimerWheel _timer_wheel;

public:
    void RunAllTask()
    {
        std::vector<Functor> functor;
        {
            std::unique_lock<std::mutex> _lock(_mutex);
            _tasks.swap(functor);
        }
        for (auto &f : functor)
        {
            f();
        }
        return;
    }
    static int CreateEventFd()
    {
        int efd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
        if (efd < 0)
        {
            LOG(ERROR, "Eventfd failed");
            abort();
        }
        return efd;
    }
    void ReadEventfd()
    {
        uint64_t res = 0;
        int ret = read(_event_fd, &res, sizeof(res));
        if (ret < 0)
        {
            if (errno == EINTR || errno == EAGAIN)
            {
                return;
            }
            LOG(ERROR, "read eventfd failed");
            abort();
        }
        return;
    }
    void WeakUpEventFd()
    {
        uint64_t val = 1;
        int ret = write(_event_fd, &val, sizeof(val));
        if (ret < 0)
        {
            if (errno == EINTR)
            {
                return;
            }
            LOG(ERROR, "read eventfd failed");
            abort();
        }
        return;
    }

public:
    EventLoop() : _thread_id(std::this_thread::get_id()),
                  _event_fd(CreateEventFd()), _event_channel(new Channel(this, _event_fd)), _timer_wheel(this)
    {
        // 给eventfd添加可读事件回调函数，读取eventfd事件通知次数
        _event_channel->SetReadCallBack(std::bind(&EventLoop::ReadEventfd, this));
        // 启动eventfd的读事件监控
        _event_channel->EnableRead();
    }
    // 用于判断当前线程是否是eventloop对应的线程
    bool IsInLoop()
    {
        return _thread_id == std::this_thread::get_id();
    }
    void AssertInLoop()
    {
        assert(_thread_id == std::this_thread::get_id());
    }
    // 判断将要执行的任务是否处于当前线程中，如果是则执行，不是则压入队列
    void RunInLoop(const Functor &cb)
    {
        if (IsInLoop())
            return cb();
        return QueueInLoop(cb);
    }
    // 将操作压入任务池
    void QueueInLoop(const Functor &cb)
    {
        {
            std::unique_lock<std::mutex> _lock(_mutex);
            _tasks.push_back(cb);
        }
        // 唤醒有可能因为没有事件就绪而导致的epoll阻塞
        // 给eventfd写入一个数据，eventfd就会触发可读时间
        WeakUpEventFd();
    }
    // 添加或修改描述符的监控事件
    void UpdateEvent(Channel *channel) { return _poller.UpdateEvents(channel); }
    // 移出描述符的监控
    void RemoveEvent(Channel *channel) { return _poller.RemoveEvent(channel); }
    void TimerAdd(uint64_t id, uint32_t delay, const TaskFunc &cb) { return _timer_wheel.TimerAdd(id, delay, cb); }
    void TimerRefresh(uint64_t id) { return _timer_wheel.TimerRefresh(id); }
    void TimerCancel(uint64_t id) { return _timer_wheel.TimerCancel(id); }
    bool HasTimer(uint64_t id) { return _timer_wheel.HasTimer(id); }

    // 事件监控--就绪事件处理--执行任务
    void Start()
    {
        while (1)
        {
            // 1.事件监控
            std::vector<Channel *> actives;
            _poller.Poll(&actives);
            // 2.事件处理
            for (auto &channel : actives)
                channel->HandleEvent();
            // 3.执行任务
            RunAllTask();
        }
    }
};

void Channel::Remove() { _loop->RemoveEvent(this); }
void Channel::Update() { _loop->UpdateEvent(this); }

void TimerWheel::TimerAdd(uint64_t id, uint32_t delay, const TaskFunc &cb)
{
    _loop->RunInLoop(std::bind(&TimerWheel::TimerAddInLoop, this, id, delay, cb));
}
// 刷新/延迟定时任务
void TimerWheel::TimerRefresh(uint64_t id)
{
    _loop->RunInLoop(std::bind(&TimerWheel::TimerRefreshInLoop, this, id));
}
void TimerWheel::TimerCancel(uint64_t id)
{
    _loop->RunInLoop(std::bind(&TimerWheel::TimerCancelInLoop, this, id));
}

class Any
{
private:
    class holder
    {
    public:
        virtual ~holder() {}
        virtual const std::type_info &type() = 0;
        virtual holder *clone() = 0;
    };
    template <class T>
    class placeholder : public holder
    {
    public:
        placeholder(const T &val) : _val(val) {}
        // 获取子类对象保存的数据类型
        virtual const std::type_info &type() { return typeid(T); }
        // 针对当前的对象自身，克隆出一个新的子类对象
        virtual holder *clone() { return new placeholder(_val); }

    public:
        T _val;
    };
    holder *_content;

public:
    Any() : _content(NULL) {}
    template <class T>
    Any(const T &val) : _content(new placeholder<T>(val)) {}
    Any(const Any &other) : _content(other._content ? other._content->clone() : NULL) {}
    ~Any() { delete _content; }

    Any &swap(Any &other)
    {
        std::swap(_content, other._content);
        return *this;
    }

    // 返回子类对象保存的数据的指针
    template <class T>
    T *get()
    {
        // 想要获取的数据类型，必须和保存的数据类型一致
        assert(typeid(T) == _content->type());
        return &((placeholder<T> *)_content)->_val;
    }
    // 赋值运算符的重载函数
    template <class T>
    Any &operator=(const T &val)
    {
        // 为val构造一个临时的通用容器，然后与当前容器自身进行指针交换，临时对象释放的时候，原先保存的数据也就被释放
        Any(val).swap(*this);
        return *this;
    }
    Any &operator=(const Any &other)
    {
        Any(other).swap(*this);
        return *this;
    }
};

typedef enum
{
    DISCONNECTED, // 连接关闭状态
    CONNECTING,   // 连接建立完成，待处理状态
    CONNECTED,    // 连接建立完成，各种设置已完成，可以通信的状态
    DISCONNECTING // 待关闭状态
} ConnStatus;

class Connection;
using PtrConnection = std::shared_ptr<Connection>;
class Connection : public std::enable_shared_from_this<Connection>
{
private:
    uint64_t _conn_id; // 连接唯一的ID，便于连接的管理和查找
    int _sockfd;       // 连接关联的文件描述符
    // uint64_t _timer_id; // 定时器ID，必须唯一，为了简化操作使用conn_id作为定时器ID
    bool _enable_inactive_release; // 连接是否启动非活跃销毁的判断标志，默认为false
    EventLoop *_loop;              // 连接所关联的一个EventLoop
    Socket _socket;                // 套接字操作管理
    Channel _channel;              // 事件管理
    Buffer _in_buffer;             // 输入缓冲区--存放从socket中读取到的数据
    Buffer _out_buffer;            // 输出缓冲区--存放要发送给对端的数据
    Any _context;                  // 请求的接收处理上下文
    ConnStatus _statu;
    using ConnectedCallBack = std::function<void(const PtrConnection &)>;
    using MessageCallBack = std::function<void(const PtrConnection &, Buffer *)>;
    using ClosedCallBack = std::function<void(const PtrConnection &)>;
    using AnyEventCallBack = std::function<void(const PtrConnection &)>;

    ConnectedCallBack _connected_callback;
    MessageCallBack _message_callback;
    ClosedCallBack _closed_callback;
    AnyEventCallBack _event_callback;
    ClosedCallBack _server_closed_callback;

private:
    // 这个接口并不是实际的发送接口，而是把数据放到发送缓冲区，启动了可写事件监控
    void SendInLoop(Buffer buff)
    {
        if (_statu == DISCONNECTED)
            return;
        _out_buffer.WriteBufferAndPush(buff);
        if (_channel.Readable() == false)
        {
            _channel.EnableWrite();
        }
    }
    // 实际释放的接口
    void ReleaseInLoop()
    {
        // 1.修改连接状态，将其置为DISCONNECTED
        _statu = DISCONNECTED;
        // 2.移除连接的事件监控 3.关闭描述符
        _channel.Remove();
        _socket.Close();
        // 4.如果当前定时器队列中还有定时销毁任务，则取消任务
        if (_loop->HasTimer(_conn_id))
            CancelInactiveReleaseInLoop();
        // 5.调用关闭回调函数，后调用服务器的回调函数，避免先移除服务器管理的连接信息导致Connection被释放，再去处理会出错
        if (_closed_callback)
            _closed_callback(shared_from_this());
        if (_server_closed_callback)
            _server_closed_callback(shared_from_this());
    }
    // 这个关闭操作并非实际的连接操作，需要判断还有没有数据待处理，待发送
    void ShutdownInLoop()
    {
        _statu = DISCONNECTING; // 设置连接为半关闭状态
        if (_in_buffer.ReadAbleSize() > 0)
            if (_message_callback)
                _message_callback(shared_from_this(), &_in_buffer);

        if (_out_buffer.ReadAbleSize() > 0)
            if (_channel.Writeable() == false)
                _channel.EnableWrite();
        if (_out_buffer.ReadAbleSize() == 0)
            ReleaseInLoop();
    }
    void EnableInactiveReleaseInLoop(int sec)
    {
        // 1.将判断标志置为true 2.添加定时销毁任务，那就刷新延迟一下 3.若不存在定时销毁任务，就新增
        _enable_inactive_release = true;
        if (_loop->HasTimer(_conn_id))
        {
            return _loop->TimerRefresh(_conn_id);
        }
        _loop->TimerAdd(_conn_id, sec, std::bind(&Connection::ReleaseInLoop, this));
    }
    void CancelInactiveReleaseInLoop()
    {
        _enable_inactive_release = false;
        if (_loop->HasTimer(_conn_id))
            _loop->TimerCancel(_conn_id);
    }

    // 五个channel的事件回调函数:
    // 描述符可读事件触发后调用的函数，接收socket数据放到接收缓冲区中，然后调用_message_callback
    void HandleRead()
    {
        // 1. 接收socket的数据放入缓冲区
        char buff[65536];
        int ret = _socket.NoBlockRecv(buff, 65535);
        if (ret < 0)
        {
            // 出错了(连接断开)，不是直接关闭连接，要先查看缓冲区是否还有数据
            return ShutdownInLoop();
        }
        else if (ret == 0) // 没有接收到数据
            return;

        // 将数据输入缓冲区
        _in_buffer.WriteAndPush(buff, ret);
        // 调用_message_callback进行业务处理
        if (_in_buffer.ReadAbleSize() > 0)
            return _message_callback(shared_from_this(), &_in_buffer);
    }
    // 描述符可写事件触发后调用的函数，将发送缓冲区中的数据进行发送
    void HandleWrite()
    {
        // _out_buffer中保存的数据就是要发送的数据
        ssize_t ret = _socket.NonBlockSend(_out_buffer.ReadPosition(), _out_buffer.ReadAbleSize());
        if (ret < 0)
        {
            // 发送错误就关闭连接
            if (_in_buffer.ReadAbleSize() > 0)
                _message_callback(shared_from_this(), &_in_buffer);
            return ReleaseInLoop(); // 这时候就是实际的关闭释放操作了
        }
        _out_buffer.MoveReadOffset(ret); // 读偏移往后移动
        if (_out_buffer.ReadAbleSize() == 0)
        {
            _channel.DisableRead(); // 无数据待发送，关闭写事件监控
            // 如果当前连接待关闭状态，则有数据，发送完数据释放连接，没有数据则直接释放
            if (_statu == DISCONNECTED)
                return ReleaseInLoop();
        }
        return;
    }
    // 描述符触发挂断事件
    void HandleClose()
    {
        // 一旦连接挂断，套接字就不干了，因此处理缓冲区的数据，再关闭连接
        if (_in_buffer.ReadAbleSize() > 0)
            _message_callback(shared_from_this(), &_in_buffer);
        return ReleaseInLoop();
    }
    // 描述符触发出错事件
    void HandleError()
    {
        return HandleClose();
    }
    // 描述符触发任意事件
    void HandleEvent()
    {
        // 刷新连接的活跃度，延迟定时销毁任务
        // 调用组件使用者的任意事件回调
        if (_enable_inactive_release == true)
            _loop->TimerRefresh(_conn_id);
        if (_event_callback)
            _event_callback(shared_from_this());
    }
    // 获取连接之后，所处状态下要进行各种设置(启动读监控，调用回调函数)
    void EstablishedInLoop()
    {
        // 1.修改连接状态 2.启动读事件监控 3.调用回调函数
        assert(_statu == CONNECTING); // 当前的状态必须一定是上层的半连接状态
        _statu = CONNECTED;           // 已连接
        // 一旦启动读事件监控就有可能会立即触发读事件，如果这时候启动了非活跃连接销毁
        _channel.EnableRead();
        if (_connected_callback)
            _connected_callback(shared_from_this());
    }
    void UpgradeInLoop(const Any &context, const ConnectedCallBack &conn, const MessageCallBack &msg,
                       const ClosedCallBack &closed, const AnyEventCallBack &event)
    {
        _context = context;
        _connected_callback = conn;
        _message_callback = msg;
        _closed_callback = closed;
        _event_callback = event;
    }

public:
    Connection(EventLoop *loop, uint64_t conn_id, int sockfd)
        : _conn_id(conn_id), _sockfd(sockfd),
          _enable_inactive_release(false), _loop(loop), _statu(CONNECTING), _socket(sockfd), _channel(loop, sockfd)
    {
        _channel.SetCloseCallBack(std::bind(&Connection::HandleClose, this));
        _channel.SetEventCallBack(std::bind(&Connection::HandleEvent, this));
        _channel.SetReadCallBack(std::bind(&Connection::HandleRead, this));
        _channel.SetWriteCallBack(std::bind(&Connection::HandleWrite, this));
        _channel.SetErrorCallBack(std::bind(&Connection::HandleError, this));
    }
    ~Connection() { LOG(DEBUG, "release connection:%p", this); }
    int Fd() { return _sockfd; }
    int Id() { return _conn_id; }
    bool Connected() { return _statu == CONNECTED; } // 是否处于CONNECTED
    // 设置上下文--连接建立完成时调用
    void SetContext(const Any &context) { _context = context; }
    // 获取上下文
    Any *GetContext(const Any &context) { return &_context; }
    void SetConnectedCallBack(const ConnectedCallBack &cb) { _connected_callback = cb; }
    void SetMessageCallBack(const MessageCallBack &cb) { _message_callback = cb; }
    void SetClosedCallBack(const ClosedCallBack &cb) { _closed_callback = cb; }
    void SetAnyEventCallBack(const AnyEventCallBack &cb) { _event_callback = cb; }
    void SetSrvClosedCallBack(const AnyEventCallBack &cb) { _server_closed_callback = cb; }
    void Send(const char *data, size_t len)
    {
        Buffer buff;
        buff.WriteAndPush(data, len);
        _loop->RunInLoop(std::bind(&Connection::SendInLoop, this, buff));
    }
    // 连接建立就绪后，进行channel回调设置，启动读监控，调用_connected_callback
    void Established()
    {
        _loop->RunInLoop(std::bind(&Connection::EstablishedInLoop, this));
    }
    // 判断有无数据待处理，不是实际关闭
    void Shutdown()
    {
        _loop->RunInLoop(std::bind(&Connection::ShutdownInLoop, this));
    }
    // 启动非活跃销毁，定义多长时间无通信就是非活跃，添加定时任务
    void EnableInactiveRelease(int sec)
    {
        _loop->RunInLoop(std::bind(&Connection::EnableInactiveReleaseInLoop, this, sec));
    }
    // 取消非活跃销毁
    void CanncelInactiveRelease()
    {
        _loop->RunInLoop(std::bind(&Connection::CancelInactiveReleaseInLoop, this));
    }
    // 切换协议--重置上下文以及阶段性处理函数-非线程安全--必须在EventLoop线程中立即执行
    // 防止新的事件触发后，处理时，切换任务还没有被执行，会导致数据使用原协议处理了
    void Upgrade(const Any &context, const ConnectedCallBack &conn, const MessageCallBack &msg,
                 const ClosedCallBack &closed, const AnyEventCallBack &event)
    {
        _loop->AssertInLoop();
        _loop->RunInLoop(std::bind(&Connection::UpgradeInLoop, this, context, conn, msg, closed, event));
    }
};

class Acceptor
{
private:
    Socket _socket;   // 用于创建监听套接字
    EventLoop *_loop; // 用于对监听套接字进行事件监控
    Channel _channel; // 用于对监听套接字进行事件管理

    using AcceptCallback = std::function<void(int)>;
    AcceptCallback _accept_callback;

private:
    // 监听套接字的读事件回调处理函数-获取新连接，调用_accept_callback函数进行新连接处理
    void HandleRead()
    {
        int new_fd = _socket.Accept();
        if (new_fd < 0)
            return;
        if (_accept_callback)
            _accept_callback(new_fd);
    }
    int CreateServer(int port)
    {
        bool ret = _socket.CreateServer(port);
        assert(ret == true);
        return _socket.Fd();
    }

public:
    Acceptor(EventLoop *loop, int port) : _socket(CreateServer(port)), _loop(loop), _channel(loop, _socket.Fd())
    {
        _channel.SetReadCallBack(std::bind(&Acceptor::HandleRead, this));
    }

    void SetAcceptCallback(const AcceptCallback &cb)
    {
        _accept_callback = cb;
    }
    void Listen() { _channel.EnableRead(); }
};

class LoopThread
{
private:
    // 用于实现_loop获取的同步关系，避免线程创建时_loop还没实例化就去获取loop
    std::mutex _mutex;
    std::condition_variable _cond;
    std::thread _thread; // EventLoop对应的线程
    EventLoop *_loop;    // EventLoop指针变量，这个对象需要在线程内实例化

    // 实例化EventLoop对象，唤醒_cond上有可能阻塞的线程，并且开始运行EventLoop模块的功能
    void ThreadEntry()
    {
        EventLoop loop;
        {
            std::unique_lock<std::mutex> lock(_mutex); // 加锁
            _loop = &loop;
            _cond.notify_all();
        }
        loop.Start();
    }

public:
    // 创建线程，设定线程入口函数
    LoopThread() : _loop(NULL), _thread(std::thread(&LoopThread::ThreadEntry, this))
    {
    }
    // 返回当前线程关联的EventLoop对象指针
    EventLoop *GetLoop()
    {
        EventLoop *loop = NULL;
        {
            std::unique_lock<std::mutex> lock(_mutex); // 加锁
            _cond.wait(lock, [&]()
                       { return _loop != NULL; }); // loop为NULL就一直阻塞
            loop = _loop;
        }
        return loop;
    }
};

class LoopThreadPool
{
private:
    int _thread_count;
    int _next_index;
    EventLoop *_baseloop;
    std::vector<LoopThread *> _threads; // 保存所有LoopThread对象
    std::vector<EventLoop *> _loops;    // 从属线程数量大于0，则从_loops中进行线程EventLoop分配

public:
    LoopThreadPool(EventLoop *baseloop) : _thread_count(0), _next_index(0), _baseloop(baseloop) {}
    // 设置线程数量
    void SetThreadCount(int count) { _thread_count = count; }
    // 创建所有的从属线程
    void Create()
    {
        if (_thread_count > 0)
        {
            _threads.resize(_thread_count);
            _loops.resize(_thread_count);
            for (int i = 0; i < _thread_count; ++i)
            {
                _threads[i] = new LoopThread();
                _loops[i] = _threads[i]->GetLoop();
            }
        }
        return;
    }
    EventLoop *NextLoop()
    {
        if (_thread_count == 0)
            return _baseloop;
        _next_index = (_next_index + 1) % _thread_count;
        return _loops[_next_index];
    }
};

class TcpServer
{
private:
    int _timerout; // 多长时间无通信就是非活跃连接
    int _port;
    bool _enable_inactive_release;                      // 是否启动非活跃连接超时销毁的判断标志
    uint64_t _next_id;                                  // 一个自动增长的连接ID
    EventLoop _baseloop;                                // 主线程的EventLoop对象，负责监听事件的处理
    Acceptor _acceptor;                                 // 监听套接字的管理对象
    LoopThreadPool _pool;                               // 从属EventLoop线程池
    std::unordered_map<uint64_t, PtrConnection> _conns; // 保存管理所有连接对应的shared_ptr对象
    using ConnectedCallBack = std::function<void(const PtrConnection &)>;
    using MessageCallBack = std::function<void(const PtrConnection &, Buffer *)>;
    using ClosedCallBack = std::function<void(const PtrConnection &)>;
    using AnyEventCallBack = std::function<void(const PtrConnection &)>;

    ConnectedCallBack _connected_callback;
    MessageCallBack _message_callback;
    ClosedCallBack _closed_callback;
    AnyEventCallBack _event_callback;
    ClosedCallBack _server_closed_callback;

private:
    void RunAfterInLoop(const Functor &task, int delay)
    {
        _next_id++;
        _baseloop.TimerAdd(_next_id, delay, task);
    }

    // 为新连接构造Connection进行管理
    void NewConnection(int fd)
    {
        _next_id++;
        PtrConnection conn(new Connection(_pool.NextLoop(), _next_id, fd));
        conn->SetMessageCallBack(_message_callback);     // 为通信套接字设置可读事件的回调函数
        conn->SetClosedCallBack(_closed_callback);       // 关闭事件的回调函数
        conn->SetConnectedCallBack(_connected_callback); // 可写事件的回调函数
        conn->SetAnyEventCallBack(_event_callback);
        conn->SetSrvClosedCallBack(std::bind(&TcpServer::RemoveConnection, this, std::placeholders::_1));
        if (_enable_inactive_release)
            conn->EnableInactiveRelease(_timerout); // 启动非活跃超时销毁
        conn->Established();                        // 就绪初始化
        _conns.insert(std::make_pair(_next_id, conn));
    }
    void RemoveConnectionInLoop(const PtrConnection &conn)
    {
        int id = conn->Id();
        auto it = _conns.find(id);
        if (it != _conns.end())
            _conns.erase(it);
        _conns.erase(id);
    }
    // 从_conns中移除连接信息
    void RemoveConnection(const PtrConnection &conn)
    {
        _baseloop.RunInLoop(std::bind(&TcpServer::RemoveConnectionInLoop, this, conn));
    }

public:
    TcpServer(int port)
        : _port(port), _next_id(0), _enable_inactive_release(false),
          _acceptor(&_baseloop, port), _pool(&_baseloop)
    {
        _acceptor.SetAcceptCallback(std::bind(&TcpServer::NewConnection, this, std::placeholders::_1));
        _acceptor.Listen(); // 将监听套接字挂到baseloop上开始监控事件
    }
    void SetThreadCount(int count) { return _pool.SetThreadCount(count); }
    void SetConnectedCallBack(const ConnectedCallBack &cb) { _connected_callback = cb; }
    void SetMessageCallBack(const MessageCallBack &cb) { _message_callback = cb; }
    void SetClosedCallBack(const ClosedCallBack &cb) { _closed_callback = cb; }
    void SetAnyEventCallBack(const AnyEventCallBack &cb) { _event_callback = cb; }
    void EnableInactiveRelease(int timeout)
    {
        _timerout = timeout;
        _enable_inactive_release = true;
    }
    // 用于添加一个定时任务
    void RunAfter(const Functor &task, int delay)
    {
        _baseloop.RunInLoop(std::bind(&TcpServer::RunAfterInLoop, this, task, delay));
    }
    void Start()
    {
        _pool.Create(); // 创建线程池中的从属线程
        return _baseloop.Start();
    }
};

class NetWork
{
public:
    NetWork()
    {
        LOG(DEBUG, "SIGPIPE INIT");
        signal(SIGPIPE, SIG_IGN);
    }
};
static NetWork nw;
#endif
